import Vue from "Vue";
import Vuex from "Vuex";
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex);
const store = new Vuex.Store({
  // 注册
  plugins: [createPersistedState()],
  state: {
    shopCarList: [],
    token: "",
    refreshToken: "",
    userInfo: {},
    address: {},
    historyIds: [],
  },
  mutations: {
    addShopCarList(state, goodsdetail) {
      let index = state.shopCarList.findIndex((item) => item.id == goodsdetail.id);
      if (index > -1) {
        state.shopCarList[index].number += goodsdetail.number;
      } else {
        state.shopCarList.push(goodsdetail);
      }
      // state.shopCarList.push(goodsdetail);
    },
    setShopCarList(state, shopCarList) {
      state.shopCarList = shopCarList;
    },
    setToken(state, token) {
      state.token = token;
    },
    setRefreshToken(state, refreshToken) {
      state.refreshToken = refreshToken;
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    setAvatar(state, avatar) {
      state.userInfo.avatar = avatar;
    },
    setAddress(state, address) {
      state.address = address;
    },
    setHistoryIds(state, historyId) {
      if (state.historyIds.some((item) => item == historyId)) {
        state.historyIds = state.historyIds.filter((item) => item !== historyId);
        if (state.historyIds.length === 10) {
          state.historyIds.pop();
        }
        state.historyIds.unshift(historyId);
      } else {
        if (state.historyIds.length === 10) {
          state.historyIds.pop();
        }
        state.historyIds.unshift(historyId);
      }
    },
  },
});
export default store;
